"""
简单的 Python 客户端示例
最基础的使用方式，适合快速上手
"""
import requests


# API 基础地址
BASE_URL = "http://localhost:8000/api"

# 存储 token
token = None


def register_user():
    """用户注册示例"""
    print("用户注册...")
    
    url = f"{BASE_URL}/auth/register"
    data = {
        "username": "simpleuser",
        "email": "simple@example.com",
        "password": "password123"
    }
    
    response = requests.post(url, json=data)
    
    if response.status_code == 201:
        user = response.json()
        print(f"✅ 注册成功！用户名：{user['username']}")
        return True
    else:
        print(f"❌ 注册失败：{response.json().get('detail', '未知错误')}")
        return False


def login():
    """用户登录示例"""
    global token
    
    print("用户登录...")
    
    url = f"{BASE_URL}/auth/login"
    data = {
        "username": "simpleuser",
        "password": "password123"
    }
    
    response = requests.post(url, data=data)
    
    if response.status_code == 200:
        result = response.json()
        token = result["access_token"]
        print(f"✅ 登录成功！Token: {token[:30]}...")
        return True
    else:
        print(f"❌ 登录失败：{response.json().get('detail', '未知错误')}")
        return False


def get_user_info():
    """获取当前用户信息示例"""
    global token
    
    if not token:
        print("❌ 请先登录")
        return
    
    print("获取用户信息...")
    
    url = f"{BASE_URL}/auth/me"
    headers = {
        "Authorization": f"Bearer {token}"
    }
    
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        user = response.json()
        print(f"✅ 当前用户：{user['username']} ({user['email']})")
    else:
        print(f"❌ 获取失败：{response.json().get('detail', '未知错误')}")


def update_user():
    """更新用户信息示例"""
    global token
    
    if not token:
        print("❌ 请先登录")
        return
    
    print("更新用户信息...")
    
    url = f"{BASE_URL}/users/me"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    data = {
        "email": "newemail@example.com"
    }
    
    response = requests.put(url, json=data, headers=headers)
    
    if response.status_code == 200:
        user = response.json()
        print(f"✅ 更新成功！新邮箱：{user['email']}")
    else:
        print(f"❌ 更新失败：{response.json().get('detail', '未知错误')}")


if __name__ == "__main__":
    print("=" * 50)
    print("简单示例：FastAPI 客户端使用")
    print("=" * 50 + "\n")
    
    # 1. 注册（如果用户已存在会失败，可以跳过）
    register_user()
    print()
    
    # 2. 登录
    if login():
        print()
        
        # 3. 获取用户信息
        get_user_info()
        print()
        
        # 4. 更新用户信息
        update_user()

